package com.company.book_store.service;

import com.company.book_store.dao.Bookinfoddao;
import com.company.book_store.dao.Ibookinfodao;
import com.company.book_store.dao.Iuserdao;
import com.company.book_store.dao.UserdaoImpl;
import com.company.book_store.pojo.Book;
import com.company.book_store.pojo.Bookinfo;
import com.company.book_store.pojo.User;

import java.sql.Date;
import java.util.Calendar;
import java.util.List;

public class UserserviceImpl implements Iuserservice{
    private Iuserdao iuserdao=new UserdaoImpl();
    private Ibookservice ibookservice=new BookserviceImpl();
    private Ibookinfodao ibookinfodao=new Bookinfoddao();
    @Override
    public User selectByidandpsw(User user) {
        User user1 = iuserdao.selectByIdandpsw(user);
        if(user1!=null)
        {
            return user1;
        }
        return null;
    }

    @Override
    public int insertUser(User user) {
        if(iuserdao.selectByusername(user)==null)
        {
            return iuserdao.insertUser(user);
        }
        return 0;
    }

    @Override
    public int borrow(String str, int id) {
        Book book=ibookservice.selectBybookid(id);
        if(book.getBook_surplus()>=1)
        {
            if(ibookservice.updatePlus(book.getId(),book.getBook_surplus()-1)==1)
            {
                Calendar c= Calendar.getInstance();
                c.add(Calendar.DATE,30);
                Date date =new Date(System.currentTimeMillis());//借书时间
                Date dd=new Date(c.getTimeInMillis());//还书时间
                Bookinfo bookinfo=new Bookinfo(str,book.getBook_name(),date,dd,id);
                //System.out.println(bookinfo);
                int res=ibookinfodao.addbookinfo(bookinfo);
                //System.out.println(res);
                return res;
            }
        }
        return 0;
    }

    @Override
    public int returnbook(int id, int book_id) {
        Book book=ibookservice.selectBybookid(book_id);
        Ibookinfoservice ibookinfoservice=new Bookinfoservice();
        if(ibookinfoservice.selectByusernameandid(id,book_id)!=null)
        {
            ibookservice.updatePlus(book.getId(),book.getBook_surplus()+1);
            ibookinfoservice.deletebookinfo(id,book_id);
            return 1;
        }
        return 0;
    }
    @Override
    public User selectByaccount(String str) {
        return iuserdao.selectByaccount(str);
    }

    @Override
    public List<User> selectall() {
        return iuserdao.selectall();
    }

    @Override
    public int updateuser(User user) {
        return iuserdao.updateuser(user);
    }

}
